package com.study.server.handler;

import com.study.server.message.GameMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.IOException;

/**
 * Created by meen on 2017/12/4.
 */
public class NettyServerHandler extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.err.println("收到消息:" + msg);
        if (msg instanceof GameMessage) {
            GameMessage message = (GameMessage) msg;
            int len = message.getInt();
            String str = message.getString();
            System.err.println("收到消息:" + len + "  " + str);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("新开会话:" + ctx.channel().id().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("会话关闭:" + ctx.channel().id().toString());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.err.println("会话异常:" + ctx.channel().id().toString());
        if (cause instanceof IOException) {
            return;
        }
        cause.printStackTrace();
    }
}
